package cn.xuqiudong.console.module.system.service;


import cn.xuqiudong.common.base.service.BaseService;
import cn.xuqiudong.console.module.system.mapper.SysDictMapper;
import cn.xuqiudong.console.module.system.model.SysDict;
import org.springframework.stereotype.Service;

/**
 * 描述:数据字典表 Service
 * @author Vic.xu
 * @since  2019-01-28 10:01
 */
@Service
public class SysDictService extends BaseService<SysDictMapper, SysDict> {

    /**
     * 判断code是否重复
     */
    public boolean checkCode(Integer id, String code) {
        return mapper.checkCode(id, code);
    }

    /**
     * 保存字典
     */
    @Override
    public int save(SysDict entity) {
        if (entity.getId() == null || entity.getId() <= 0) {
            generatorSyscode(entity);
        }
        return super.save(entity);
    }

    /**
     * 根据id删除记录 以及子类
     */
    @Override
    public int delete(int id) {
        return mapper.deleteSelfAndSub(id);
    }


    /**
     * 产生系统编码
      * @param entity字典 entity
     */
    private void generatorSyscode(SysDict entity) {
        Integer pid = entity.getPid();
        // 当不存在父节点的时候  则把自己的code设置为syscode
        if (pid == null || pid <= 0) {
            entity.setSysCode(entity.getCode());
            return;
        }
        SysDict parent = findById(pid);
        //存在父节点 : 则父节点sysCode + 当前code
        if (parent != null) {
            entity.setSysCode(parent.getSysCode() + "-" + entity.getCode());
        }
    }

    @Override
    protected boolean hasAttachment() {
        return false;
    }
}
